<?php

namespace app\wechat\models;

use app\wechat\core\BaseModel;
use cm;
use common\models\UserBalance;
use common\models\UserRebate;
use Yii;
use yii\helpers\Url;
use common\models\CmDataModel;

class UserModel extends BaseModel
{
	/*
	*获取用户个人信息
	*/
	public function actionInfo(){
		$sql = "SELECT id,name,telephone,id_card AS idcard,id_img_p,id_img_b,nickname,head_img,sex FROM user WHERE openid='{$this->openid}' AND status=1";
		$info = Cm::$db->one($sql);
		if(empty($info)){
			Cm::$res->error('该用户不存在');	
		}
		foreach ($info as $key => &$value) {
			if(empty($value) && $key != 'sex'){
				$value = "";
			}
		}
		Cm::$res->susess($info);
	}

	/*
	*获取常联系人
	*/
	public function actionContacts(){
		$id = (int)Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
		$where = empty($id) ? "" : " AND a.id={$id} ";
		$sql = "SELECT a.id,a.name,a.telephone,a.id_card as idcard FROM user_contacts a INNER JOIN user b ON b.id=a.uid WHERE b.openid='{$this->openid}' AND b.status=1 AND a.status=1 {$where}";
		$resdata = Cm::$db->all($sql);
		Cm::$res->susess($resdata);
	}

	/*
	*添加常用联系人
	*/
	public function actionAddcontacts(){
		$time = date("Y-m-d H:i:s",time());
		$data = [
			'name' => Cm::$req->post('name', ['title' => '姓名']),
			'telephone' => Cm::$req->post('telephone', ['title' => '联系方式']),
			'id_card' => Cm::$req->post('idcard', ['title' => '身份证']),
			'addtime' => $time,
			'updatetime' => $time
		];
		$user = Cm::$db->one("SELECT a.id,(SELECT count(id) as num FROM user_contacts WHERE uid=a.id AND id_card='{$data['id_card']}' AND status=1) as hasidcard FROM user a WHERE a.openid='{$this->openid}'");
		if(empty($user['id'])){
			Cm::$res->error('该用户未找到');	
		}
		if($user['hasidcard']>0){
			Cm::$res->error('该常用联系人已存在');		
		}
		$data['uid'] = $user['id'];
		$exitidcard = $this->juheCheckIdcard($data['id_card'],$data['name']);
		if(!$exitidcard){
			Cm::$res->error('请输入正确的身份证');	
		}
		if(!preg_match("/^1[3456789]\d{9}$/", $data['telephone'])){
			Cm::$res->error('请输入正确的联系方式');
		}
		$id = Cm::$db->insert("user_contacts", $data);
		if($id){
			Cm::$res->susess(['id'=>$id],"保存成功");
		}else{
			Cm::$res->error('保存失败');
		}
	}

	/*
	*编辑常用联系人
	*/
	public function actionEditcontacts(){
		$time = date("Y-m-d H:i:s",time());
		$id = (int)Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
		if(empty($id)){
			Cm::$res->error('请选择保存的常用联系人');
		}
		$data = [
			'name' => Cm::$req->post('name', ['title' => '姓名']),
			'telephone' => Cm::$req->post('telephone', ['title' => '联系方式']),
			'id_card' => Cm::$req->post('idcard', ['title' => '身份证']),
			'updatetime' => $time
		];
		$exitid = Cm::$db->one("SELECT id FROM user_contacts WHERE id={$id}");
		if(empty($exitid)){
			Cm::$res->error('该常用联系人不存在');	
		}
		$user = Cm::$db->one("SELECT id FROM user WHERE openid='{$this->openid}'");
		if(empty($user['id'])){
			Cm::$res->error('参数错误');	
		}
		$data['uid'] = $user['id'];
		$exitidcard = $this->juheCheckIdcard($data['id_card'],$data['name']);
		if(!$exitidcard){
			Cm::$res->error('请输入正确的身份证');	
		}
		if(!preg_match("/^1[3456789]\d{9}$/", $data['telephone'])){
			Cm::$res->error('请输入正确的联系方式');
		}
		Cm::$db->update("user_contacts", $data," id={$id}");
		Cm::$res->susess([],'保存成功');
	}

	/*
	*删除常用联系人
	*/
	public function actionDelcontacts(){
		$id = (int)Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
		$exitid = Cm::$db->one("SELECT id FROM user_contacts WHERE id={$id}");
		if(empty($exitid)){
			Cm::$res->error('该常用联系人不存在');	
		}
		Cm::$db->update("user_contacts", ['status'=>2,'updatetime'=>date("Y-m-d H:i:s",time())]," id={$id}");
		Cm::$res->susess([],'删除成功');
	}

	/*
	*添加意见反馈
	*/
	public function actionAddfeedback(){
		$time = date("Y-m-d H:i:s",time());
		$data = [
			'content' => Cm::$req->post('content', ['title' => '意见反馈']),
			'addtime' => $time,
			'updatetime' => $time,
			'status' => 1
		];
		$user = Cm::$db->one("SELECT id FROM user WHERE openid='{$this->openid}'");
		if(empty($user['id'])){
			Cm::$res->error('参数错误');	
		}
		$data['uid'] = $user['id'];
		$id = Cm::$db->insert("feedback", $data);
		if($id){
			Cm::$res->susess([],"保存成功");
		}else{
			Cm::$res->error('保存失败');
		}
	}

	/*
	*上传图片
	*/
	public function actionUpload(){
		(new CmDataModel())->upload('headimg','img');
	}

	/*
	*个人中心
	*/
	public function actionPersonal(){
		$user = Cm::$db->one("SELECT id,nickname,head_img FROM user WHERE openid='{$this->openid}'");
		$config = Cm::$db->one("SELECT value FROM config_setting WHERE `group`='sys' AND `key`='sys_telephone' AND status=1 ");
		if(!empty($user['id'])&&!($model=UserBalance::findOne($user['id']))){
            $model=new UserBalance();
            $model->uid=$user['id'];
            $model->balance=0;
            if(!$model->save())Cm::$res->error('数据获取异常');
        }
		$date = [
			'nickname'=>empty($user['nickname'])?'':$user['nickname'],
			'head_img'=>empty($user['head_img'])?'':$user['head_img'],
			'sys_telephone'=>empty($config['value'])?'':$config['value'],
            'balance'=>$model->balance,
            'way_balance'=>UserRebate::find()->andWhere(['status'=>UserRebate::STATUS_PASS,'type'=>UserRebate::TYPE_GET])->sum('money'),
            'id'=>$user['id']
		];
		Cm::$res->susess($date);
	}

	/*
	*保存个人信息
	*/
	public function actionSaveinfo(){
		$time = date("Y-m-d H:i:s",time());
		$data = [
			'name' => Cm::$req->post('name', ['title' => '姓名']),
			'telephone' => Cm::$req->post('telephone', ['title' => '联系方式']),
			'id_card' => Cm::$req->post('idcard', ['title' => '身份证']),
			'nickname' => Cm::$req->post('nickname', ['title' => '昵称']),
			'head_img' => Cm::$req->post('headimg', ['title' => '头像']),
			'id_img_p' => Cm::$req->post('idimgp', ['null', 'empty', 'default' => '']),
			'id_img_b' => Cm::$req->post('idimgb', ['null', 'empty', 'default' => '']),
			'updatetime' => $time
		];
		$user = Cm::$db->one("SELECT id FROM user WHERE openid='{$this->openid}'");
		if(empty($user['id'])){
			Cm::$res->error('参数错误');	
		}
		$exitidcard = $this->juheCheckIdcard($data['id_card'],$data['name']);
		if(!$exitidcard){
			Cm::$res->error('请输入正确的身份证');	
		}
		if(!preg_match("/^1[3456789]\d{9}$/", $data['telephone'])){
			Cm::$res->error('请输入正确的联系方式');
		}
		Cm::$db->update("user", $data," id={$user['id']}");
		Cm::$res->susess([],'保存成功');
	}

	/**
	 * 判断是否为合法的身份证号码,聚合验证
	 * @param $idcard
	 * @param $name
	 * @return bloat
	 */
	private function juheCheckIdcard($idcard,$name){
		$key = Yii::$app->params['juhe']['key'];
		$url = "http://op.juhe.cn/idcard/query?key=".$key."&idcard=".$idcard."&realname=".$name;
		$resStr = Cm::$curl->get($url);
		if($resStr === false){
			return false;
		}else{
			$resStr = json_decode($resStr,true);
			if($resStr['error_code'] == 0 && !empty($resStr['result']) && $resStr['result']['res']==1){
				return true;
			}else{
				return false;
			}
		}
	}

	/**
	 * 判断是否为合法的身份证号码
	 * @param $idcard
	 * @return bloat
	 */
	private function isCreditNo($vStr){
		$vCity = array('11','12','13','14','15','21','22','23','31','32','33','34','35','36','37','41','42','43','44','45','46','50','51','52','53','54','61','62','63','64','65','71','81','82','91');
	 	if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)){
	  		return false;
	 	}
	 	if (!in_array(substr($vStr, 0, 2), $vCity)){
	 		return false;	
	 	} 
	 	$vStr = preg_replace('/[xX]$/i', 'a', $vStr);
	 	$vLength = strlen($vStr);
	 	if ($vLength == 18) {
	  		$vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
	 	} else {
	  		$vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
	 	}
	 	if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) {
	 		return false;
	 	}
 		if ($vLength == 18) {
  			$vSum = 0;
  			for ($i = 17 ; $i >= 0 ; $i--) {
   				$vSubStr = substr($vStr, 17 - $i, 1);
   				$vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
  			}
  			if($vSum % 11 != 1){
  				return false;	
  			} 
 		}
	 	return true;
	}
}